package com.wealth.coupon.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import com.wealth.coupon.util.LabelFileEncrypt;
import com.wealth.coupon.util.LabelFileUtil;

/**
 * 生码服务
 * @author chan
 */
@Component
public class MakeLabelService {

	Logger logger = Logger.getLogger(MakeLabelService.class);

	private String labelFilePath = "";			/** 标签文件 磁盘存放路径 */
	private String labelUrlPath = "";			/** 标签文件 下载链接 */

	public String getLabelFilePath() {
		return labelFilePath;
	}
	public void setLabelFilePath(String labelFilePath) {
		this.labelFilePath = labelFilePath;
	}
	public String getLabelUrlPath() {
		return labelUrlPath;
	}
	public void setLabelUrlPath(String labelUrlPath) {
		this.labelUrlPath = labelUrlPath;
	}
	/**
	 * 生成优惠卷规则
	 * modify by chan on 2016-09-09
	 */
	public String createLabel(String uid,int start,int end) throws Exception {

		try {
			//1.相对目录，apache反向代理
			String filesuffix ="/upload/label/"+new DateTime().toString("yyyyMMdd")+"/"+uid+".txt";
					
			//2.绝对目录
			String filePath = labelFilePath + filesuffix; 		//磁盘目录
			String urlPath= labelUrlPath + filesuffix; 	//下载连接 如：http://
			File file=new File(filePath);							//如果文件存在，就删除
			if(file.exists()){
				file.delete();
			}
			
			//3.生码
			LabelFileUtil.saveToFile("优惠券\t\t", filePath);
			LabelFileUtil.saveToFileEx("\r\n".getBytes(), filePath, true);
			List<String> codeList = new ArrayList<String>();
			for (int i = start; i <=end; i++) {
				//加密
				String code=LabelFileEncrypt.encrypt(uid, i)+"\r\n";				
				codeList.add(code);
			}

			// 生成文件默认全部加密处理
			StringBuffer line = new StringBuffer();
			// 打乱顺序
			int num = 0;
			Collections.shuffle(codeList);
			if (codeList.size() > 0) {
				for (String sline : codeList) {
					line.append(sline);
					num++;
					if (num >= 2000) {
						LabelFileUtil.saveToFileEx(line.toString().getBytes(), filePath, true);
						line.setLength(0);
						num = 0;
					}
				}

				if (num > 0) {
					LabelFileUtil.saveToFileEx(line.toString().getBytes(), filePath, true);
					logger.info(line.toString());	
					line.setLength(0);
					num = 0;
				}
			}
			return urlPath;
		} catch (Exception e) {
			logger.error("制作生成 标签文件失败，请检查磁盘目录是否正确", e);
			logger.error(e.fillInStackTrace(), e);
			return null;
		}
	}



}
